﻿using System;
using System.Diagnostics;

namespace NazTek.Utility
{
    /// <summary>
    /// Encapsulates and sets default event logging metadata.
    /// </summary>
    public class EventLogMetadata
    {
        /// <summary>
        /// Sets default <see cref="Source"/> (Miscellaneous), <see cref="EventId"/> (0), 
        /// and <see cref="EntryType"/> (<see cref="EventLogEntryType.Information"/>).
        /// </summary>
        public EventLogMetadata()
        {
            LogType = "Application";
            Source = "Miscellaneous";
            EventId = 0;
            EntryType = EventLogEntryType.Information;
        }
        /// <summary>
        /// Gets/set source name to apply to the event entry.
        /// </summary>
        public string Source { get; set; }
        /// <summary>
        /// Gets/sets log category name.
        /// </summary>
        public string LogType { get; set; }
        /// <summary>
        /// Gets/sets log entry description.
        /// </summary>
        public string LogEntryDescription { get; set; }
        /// <summary>
        /// Gets/sets event id.
        /// </summary>
        public int EventId { get; set; }
        /// <summary>
        /// Gets/sets event entry type.
        /// </summary>
        public EventLogEntryType EntryType { get; set; }
        /// <summary>
        /// Writes event log entry.
        /// </summary>
        /// <param name="message">Log message.</param>
        internal void WriteEntry(string message)
        {
            if (!EventLog.SourceExists(Source))
                CreateEventSource();
            EventLog.WriteEntry(Source, message, EntryType, EventId);
        }
        /// <summary>
        /// Attempts to create event source, first via <see cref="EventLog.CreateEventSource(string,string)"/> API and
        /// if that fails then via command shell.
        /// </summary>
        /// <remarks>Any exception is suppressed.</remarks>
        private void CreateEventSource()
        {
            try
            {
                EventLog.CreateEventSource(Source, LogType);
            }
            catch (Exception)
            {
                try
                {
                    var cmdText = string.Format(@"eventcreate /ID {0} /L {1} /T INFORMATION  /SO {2} /D ""{3}""",
                        EventId, LogType, Source, LogEntryDescription);
                    using (Process.Start("CMD.exe", cmdText)) { }
                }
                catch (Exception)
                {
                    // suppress
                }
            }
        }
    }
}